package com.travel.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import com.travel.core.AbstractDao.Direction;
import com.travel.core.DaoFactory;
import com.travel.dao.IHotelDao;
import com.travel.entities.Hotel;

public class TopHotHotelsServlet extends HttpServlet {

    private static final long serialVersionUID = -1312433669258345798L;

    private static final Logger LOGGER = LogManager.getLogger(TopHotHotelsServlet.class);

    private static final IHotelDao HOTEL_DAO = DaoFactory.getDao(IHotelDao.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String type = request.getParameter("type");
        String orderBy;
        if ("0".equals(type)) {
            // 按评价数
            orderBy = "comment_point";
        } else if ("1".equals(type)) {
            orderBy = "comment_score";
        } else {
            orderBy = "comment_count";
        }
        List<Hotel> hotels = HOTEL_DAO.selectListOrderBy(null, orderBy, Direction.DESC);
        JSONArray jsonArray = new JSONArray();
        for (Hotel u : hotels) {
            JSONObject json = new JSONObject();
            try {
                json.put("hotelName", u.getHotelName());
                json.put("hotelUrl", u.getHotelUrl());
                json.put("hotelCommentPoint", u.getHotelCommentPoint());
                json.put("hotelCommentScore", u.getHotelCommentScore());
                json.put("hotelCommentCount", u.getHotelCommentCount());
            } catch (Exception e) {
                LOGGER.error(e.getLocalizedMessage(), e);
            }
            jsonArray.put(json);
        }
        response.setCharacterEncoding("utf-8");
        response.getWriter().append(jsonArray.toString());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
